<template>
  <div class="table">
    <div class="container">
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item><i class="el-icon-search"></i> 查询条件：</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row :gutter="10">
        <el-col :xl="6"
                :lg="8"
                :md="12"
                :sm="24"
                style="margin-bottom:10px">
          <el-input v-model.trim="searchCondition.username"
                    placeholder="用户名"></el-input>
        </el-col>
        <el-col :xl="6"
                :lg="8"
                :md="12"
                :sm="24"
                style="margin-bottom:10px">
          <el-input v-model.trim="searchCondition.phoneNum"
                    placeholder="手机号"></el-input>
        </el-col>
        <el-col :xl="6"
                :lg="8"
                :md="12"
                :sm="24"
                style="margin-bottom:10px">
          <el-input v-model.trim="searchCondition.unionId"
                    placeholder="unionId"></el-input>
        </el-col>
        <el-col :xl="6"
                :lg="8"
                :md="12"
                :sm="24"
                style="margin-bottom:10px">
          <el-button type="success"
                     icon="el-icon-search"
                     :disabled="disabledbtn"
                     @click="searchInfo">搜索</el-button>
          <el-button type="warning"
                     icon="el-icon-refresh"
                     :disabled="disabledbtn"
                     @click="resetSearch">重置</el-button>
        </el-col>
      </el-row>
      <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 查询结果：</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="handle-box">
        <!-- <el-button type="primary"
                   icon="el-icon-plus"
                   class="mr10"
                   :disabled="disabledbtn"
                   @click="addData">新增</el-button> -->
        <!-- <el-button type="danger"
                   icon="el-icon-delete"
                   class="mr10"
                   :disabled="disabledbtn"
                   @click="batchDelete('deleteUserInfo')">批量删除</el-button> -->
      </div>
      <el-table :data="tableData"
                border
                class="table"
                ref="multipleTable"
                v-loading="loading"
                :reserve-selection="true"
                @row-dblclick="rowDblclick">
        <el-table-column type="index"
                         align="center"> </el-table-column>
        <el-table-column type="selection"
                         width="55"
                         align="center"></el-table-column>
        <el-table-column prop="headImgUrl"
                         label="头像"
                         width="150"
                         align="center">
          <template slot-scope="scope">
            <el-image style="width: 60px; height: 60px"
                      :src="formatImg(scope.row.headImgUrl)"
                      :preview-src-list="formatImgList(scope.row)">
            </el-image>
          </template>
        </el-table-column>

        <el-table-column prop="username"
                         label="用户名"
                         align="center">
        </el-table-column>
        <el-table-column prop="name"
                         label="昵称"
                         align="center">
        </el-table-column>
        <el-table-column prop="realName"
                         label="真实姓名"
                         align="center">
        </el-table-column>
        <el-table-column prop="phoneNum"
                         label="手机号"
                         align="center">
        </el-table-column>

        <el-table-column prop="unionId"
                         label="unionId"
                         align="center">
        </el-table-column>
        <el-table-column label="操作"
                         width="180"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       icon="el-icon-view"
                       @click="handleViewEdit(scope.$index, scope.row, 'view', '查看')">查看</el-button>
            <el-button type="text"
                       icon="el-icon-shopping-bag-1"
                       @click="handleAuctionRecord(scope.$index, scope.row)">拍卖纪录</el-button>
            <el-button type="text"
                       icon="el-icon-s-finance"
                       @click="handleRechargeRecord(scope.$index, scope.row)">用户资金</el-button>
            <!-- <el-button type="text"
                       icon="el-icon-edit"
                       @click="handleViewEdit(scope.$index, scope.row, 'edit', '编辑')">编辑</el-button> -->
            <!-- <el-button type="text"
                       icon="el-icon-delete"
                       class="red"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->

            <div class="mlr10 display-inline-block">
              <el-popconfirm placement="top"
                             width="160"
                             title="你确定要删除吗?"
                             @confirm="deleteRow('deleteUserInfo')">
                <el-button type="text"
                           icon="el-icon-delete"
                           class="red"
                           slot="reference"
                           @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       layout="total, sizes, prev, pager, next, jumper"
                       :page-size="searchCondition.size"
                       :current-page="searchCondition.current"
                       :page-sizes="pageSizes"
                       :total="total"
                       :hide-on-single-page="false">
        </el-pagination>
      </div>
    </div>

    <!-- 新增编辑查看弹出框 -->
    <el-dialog :title="dialogTitle"
               :visible.sync="editVisible"
               width="60%"
               :close-on-click-modal="closeOnClickModal"
               @closed="closedFormDialog">
      <el-form ref="userForm"
               :model="userForm"
               :rules="rules"
               v-loading="loadingDialog"
               label-width="150px">
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="用户名："
                          prop="username">
              <el-input v-model.trim="userForm.username"
                        placeholder="用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="手机号："
                          prop="phoneNum">
              <el-input v-model.trim="userForm.phoneNum"
                        placeholder="手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="昵称："
                          prop="name">
              <el-input v-model.trim="userForm.name"
                        placeholder="用户姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="unionId："
                          prop="unionId">
              <el-input v-model.trim="userForm.unionId"
                        placeholder="用户唯一性编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="10">
            <el-form-item label="头像：">
              <el-upload class="avatar-uploader"
                         :action="uploadUrl"
                         :data="uploadData"
                         :show-file-list="false"
                         name="file"
                         :on-success="handleAvatarSuccess"
                         :on-error="handleAvatarError"
                         :before-upload="beforeAvatarUpload">
                <img v-if="userImg"
                     :src="userImg"
                     class="avatar" />
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelSubmit('userForm')">取 消</el-button>
        <el-button type="primary"
                   :disabled="disabledbtn"
                   v-if="!isDisabledbtn"
                   @click="submitForm('userForm', userForm,methodType,'commonUserInfoListInfo','getAppUserListInfo')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 用户金额信息 -->
    <el-dialog title="提示"
               :visible.sync="dialogVisible"
               width="30%"
               :before-close="handleClose">
      <div class="user-money">
        <ul class="clearfix">
          <li class="bg"><span class="name">今日充值</span>
            <div>￥{{userMoneyData.dayRecharge}}</div>
          </li>
          <li class="bg">
            <span class="name">总充值</span>
            <div>￥{{userMoneyData.totalRecharge}}</div>
          </li>
          <li>
            <span class="name">今日收益</span>
            <div>￥{{userMoneyData.dayIncome}}</div>
          </li>
          <li>
            <span class="name">总收益</span>
            <div>￥{{userMoneyData.income}}</div>
          </li>
          <li class="bg">
            <span class="name">今日提现</span>
            <div>￥{{userMoneyData.dayWithdraw}}</div>
          </li>
          <li class="bg">
            <span class="name">总提现</span>
            <div>￥{{userMoneyData.totalWithdraw}}</div>
          </li>
          <li class="color-orange">
            <span class="name">余额</span>
            <div>￥{{userMoneyData.availableBalance}}</div>
          </li>
          <li>
            <span class="name">冻结金额</span>
            <div>￥{{userMoneyData.accountFrozen}}</div>
          </li>
        </ul>
      </div>
      <!-- <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AppUserInfo',
  data() {
    return {
      tableData: [] /* 表格中所有数据 */,
      selectTableData: [] /* 选中行数据 */,
      selectRole: [],

      dialogTitle: '' /* 新增编辑标题 */,
      editVisible: false /* 新增编辑显示隐藏 */,
      delVisibleType: 'delete' /* 删除类型（单选，多选） */,
      disabledbtn: false /* 按钮可用与不可用 */,
      isDisabledbtn: false /* 按钮显示或隐藏 */,

      dialogVisible: false,
      /* 是否可以通过点击 modal 关闭 Dialog	 */
      closeOnClickModal: false,

      loading: true,
      loadingDialog: false /* 对话框中数据提交加载 */,
      showType: 'add' /* 用于对话框显示 类型标记 */,
      methodType: 'POST' /* 请求类型 */,

      total: 0 /* 总数 */,
      current: 1 /* 第几页 */,
      pageSizes: [10, 20, 30, 40, 50, 100],

      /* 查询条件 */
      searchCondition: {
        username: '',
        phoneNum: '',
        unionId: '',
        current: 1,
        size: 10
      },

      /* 表单数据 */
      userForm: {
        id: '',
        username: '',
        unionId: '123456',
        name: '',
        phoneNum: '',
        headImgUrl: ''
      },
      booleanGender: false,
      userImg: '',
      /* 校验规则 */
      rules: {
        username: [{ required: true, message: '用户名必填', trigger: 'blur' }],
        name: [{ required: true, message: '用户姓名必填', trigger: 'blur' }],
        phoneNum: [{ required: true, message: '手机号必填', trigger: 'blur' }]
      },
      /* 删除时所需的编号 删除时的id */
      id: -1,
      uploadData: {
        token: ''
      },

      /* 用户金额 */
      userMoneyData: {
        accountFrozen: '',
        availableBalance: '',
        dayIncome: '',
        dayRecharge: '',
        dayWithdraw: '',
        income: '',
        totalRecharge: '',
        totalWithdraw: ''
      }
    };
  },
  created() {
    /* 获取表格信息 */
    this.getAppUserListInfo();
  },
  computed: {
    /* 格式化头像(放到查看) */
    formatImgList() {
      return function (row) {
        let array = [];
        var test = new RegExp('^http');
        let headImgUrl = row.headImgUrl;
        if (test.test(headImgUrl)) {
          array.push(headImgUrl);
          return array;
        }
        array.push(this.imageUrl + headImgUrl);
        return array;
      };
    }
  },
  methods: {
    /* 格式化头像 */
    formatImg(headImgUrl) {
      var test = new RegExp('^http');
      if (test.test(headImgUrl)) {
        return headImgUrl;
      }
      return this.imageUrl + headImgUrl;
    },

    /* 每页显示几条 */
    handleCurrentChange(val) {
      this.searchCondition.current = val;
      this.getAppUserListInfo();
    },

    /* 显示第几页 */
    handleSizeChange(val) {
      this.searchCondition.size = val;
      this.getAppUserListInfo();
    },

    /* 请求：获取表格中数据 */
    getAppUserListInfo() {
      this.disabledbtn = true;
      this.loading = true;
      this.Request.getAppUserListInfo(this.searchCondition)
        .then((res) => {
          this.disabledbtn = false;
          this.loading = false;
          if (res.status === 1) {
            this.tableData = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          this.disabledbtn = false;
          this.loading = false;
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 双击当前行 */
    rowDblclick(row, column, event) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },

    /* 点击编辑按钮 */
    handleViewEdit(index, row, code, name) {
      if ('view' === code) {
        this.dialogTitle = name;
        this.isDisabledbtn = true;
        this.closeOnClickModal = true;
      } else if ('edit' === code) {
        this.dialogTitle = name;
        this.methodType = 'PUT';
      }
      this.userForm.id = row.id;
      this.userForm.username = row.username;
      this.userForm.name = row.name;
      this.userForm.unionId = row.unionId;
      this.userForm.phoneNum = row.phoneNum;
      this.userForm.headImgUrl = row.headImgUrl;

      var test = new RegExp('^http');
      if (test.test(row.headImgUrl)) {
        this.userImg = row.headImgUrl;
      } else {
        this.userImg = this.imageUrl + row.headImgUrl;
      }

      this.showType = code;
      this.editVisible = true;
    },

    /* 跳转到拍卖纪录页面 */
    handleAuctionRecord(index, row) {
      this.$router.push({ name: 'sessionInfo', params: { userId: row.id } });
    },

    /* 查询用户资金信息 */
    handleRechargeRecord(index, row) {
      /* 获取用户金额信息 */
      this.dialogVisible = true;
      this.getUserMoneyCountInfo(row.id);
    },

    /* 请求：获取表格中数据 */
    getUserMoneyCountInfo(id) {
      // this.disabledbtn = true;
      // this.loading = true;
      this.Request.getUserMoneyCountInfo({ id: id })
        .then((res) => {
          // this.disabledbtn = false;
          // this.loading = false;
          if (res.status === 1) {
            console.log(res);
            this.userMoneyData.accountFrozen = res.data.accountFrozen;
            this.userMoneyData.availableBalance = res.data.availableBalance;
            this.userMoneyData.dayIncome = res.data.dayIncome;
            this.userMoneyData.dayRecharge = res.data.dayRecharge;
            this.userMoneyData.dayWithdraw = res.data.dayWithdraw;
            this.userMoneyData.income = res.data.income;
            this.userMoneyData.totalRecharge = res.data.totalRecharge;
            this.userMoneyData.totalWithdraw = res.data.totalWithdraw;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          this.disabledbtn = false;
          this.loading = false;
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 点击删除按钮 */
    handleDelete(index, row) {
      this.id = row.id;
      this.delVisibleType = 'delete';
    },

    /* 搜索 */
    searchInfo() {
      /* 重置到第一页 */
      this.searchCondition.current = 1;
      this.searchCondition.size = 10;
      this.getAppUserListInfo();
    },

    /* 重置搜索内容 */
    resetSearch() {
      this.searchCondition.username = '';
      this.searchCondition.phoneNum = '';
      this.searchCondition.unionId = '';
      this.searchInfo();
    },

    /* 新增 */
    addData() {
      this.dialogTitle = '新增';
      this.editVisible = true;
    },

    /* 批量删除 */
    batchDelete(method) {
      /* 获取选中的数据 */
      let selection = this.$refs.multipleTable.store.states.selection;
      this.selectTableData = selection;
      if (selection.length > 0) {
        this.delVisibleType = 'batchDelete';
        this.deleteRow(method);
      } else {
        this.$message.warning('请至少选择一条数据');
      }
    },

    /* 关闭新增编辑查看 弹出框事件 */
    closedFormDialog() {
      /* 初始化数据使用clearValidate清空校验，
        resetFields方法在点击编辑而后点击新增时是无效的，
        所以还是要手动初始化所有的值
      */
      this.isDisabledbtn = false;
      this.userForm.id = '';
      this.userForm.username = '';
      this.userForm.name = '';
      this.userForm.phoneNum = '';
      this.userForm.userImg = '';
      this.userImg = '';
      this.booleanGender = false;
      this.closeOnClickModal = false;

      this.showType = 'add';
      this.methodType = 'POST';
      this.$refs['userForm'].clearValidate();
    },

    /* 保存或编辑 */
    submitForm(formName, formData, type, method, refreshMethod) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitFormInfo(formData, type, method, refreshMethod);
        } else {
          /* 提示还有需要填写的信息 */
          this.$message.warning('请填写所有必填信息');
          return false;
        }
      });
    },

    /**
     * 保存或编辑信息
     * formData:提交的数据
     * type:请求类型
     * method: 请求方法
     * refreshMethod: 刷新数据的方法
     */
    submitFormInfo(formData, type, method, refreshMethod) {
      /* 防止多次提交 */
      this.disabledbtn = true;
      this.loadingDialog = true;
      this.Request[method](formData, type)
        .then((res) => {
          this.disabledbtn = false;
          this.loadingDialog = false;
          if (res.status === 1) {
            this.editVisible = false;
            this.$message.success(res.msg);
            /* 重新刷新数据 */
            this[refreshMethod]();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          this.disabledbtn = false;
          this.loadingDialog = false;
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 保存或编辑 取消提交 */
    cancelSubmit(formName) {
      /* bug原因，不用api提供的方法 不信你试试 */
      // this.$refs[formName].resetFields();
      this.editVisible = false;
    },

    /* 确定删除 */
    deleteRow(method) {
      if (
        this.delVisibleType !== 'delete' &&
        this.delVisibleType !== 'batchDelete'
      ) {
        this.$message.error(`别偷偷的修改特定的参数哦`);
        return;
      }
      let selection = [];
      let length = 0;
      /* 获取要删除数据的id值数组 (单个与批量删除相同) */
      let idArray = [];
      if (this.delVisibleType === 'delete') {
        idArray.push(this.id);
      } else if (this.delVisibleType === 'batchDelete') {
        /*获取选中的值 */
        selection = this.$refs.multipleTable.store.states.selection;
        length = selection.length;
        for (let i = 0; i < length; i++) {
          idArray.push(selection[i].id);
        }
      }
      /* 删除一条或多条数据 */
      this.deleteInfo({ idArray: idArray }, method);
    },

    /* 删除后的信息 */
    deleteInfo(data, method) {
      this.disabledbtn = true;
      this.loading = true;
      this.Request[method](data)
        .then((res) => {
          this.disabledbtn = false;
          this.loading = false;
          if (res.status === 1) {
            /* 当删除成功后，删除对应选中的数据或单个数据 */
            for (let j = this.tableData.length - 1; j >= 0; j--) {
              for (let i = 0; i < data.idArray.length; i++) {
                if (data.idArray[i] === this.tableData[j].id) {
                  this.tableData.splice(j, 1);
                  break;
                }
              }
            }
            this.$message.success(`成功删除了${data.idArray.length}条数据`);
            this.selectTableData = []; /* 清除选中的数据 */
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          this.disabledbtn = false;
          this.loading = false;
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    },

    /* 关闭对话框 */
    handleClose() {
      this.dialogVisible = false;
    },

    /* 上传成功 */
    handleAvatarSuccess(file) {
      this.loadingDialog = false;
      this.personalForm.userImg = file.key;
      this.userImg = this.imageUrl + file.key;
      // this.setPersonalInfo(this.personalForm);
    },

    /* 上传失败 */
    handleAvatarError(err, file, fileList) {
      this.loadingDialog = false;
      this.$message.warning('长时间逗留，请关闭该页面后在打开');
    },

    /* 上传图片前先校验图片大小
        此处可用于获取上传凭证
    */
    beforeAvatarUpload(file) {
      const isLt500K = file.size / 1024 / 1024 < 0.5;
      this.loadingDialog = true;
      if (!isLt500K) {
        this.$message.warning(
          '上传头像图片大小不能超过 500k,请压缩后上传图片!'
        );
        this.loadingDialog = false;
        return false;
      }
      if (this.uploadData.token !== '') {
        return true;
      }
      return this.getUploadToken();
    },

    /* 获取七牛云token */
    getUploadToken() {
      return this.Request.getUploadToken({})
        .then((res) => {
          if (res.status === 0) {
            this.uploadData.token = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((res) => {
          //this.$message.error("服务器繁忙，请稍后再试");
        });
    }
  }
};
</script>

<style scoped>
/* layout-布局 */
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}

.textAlignCenter {
  text-align: center;
}

/* 修改select的盒模型 */
.el-select {
  display: block;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 修改该属性值  查询条件，查询结果得样式 */
.el-breadcrumb {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

/* 对话框中自定义样式 */
.user-money ul li {
  float: left;
  width: 46%;
  padding: 10px;
  font-size: 24px;
  font-weight: bold;
  color: #332019;
  border-radius: 6px;
}

.user-money ul li .name {
  font-size: 12px;
  color: #988f8c;
}

.user-money ul li.bg {
  background-color: #f8f8f8;
}

.user-money ul .color-orange {
  color: #f36d3c;
}
</style>

/* scoped 不要添加 */
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  display: block;
  width: 178px;
  height: 178px;
  object-fit: cover;
}

.el-upload--text {
  width: auto;
}

/* 修改Switch开关 */
.el-switch {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
</style>
